<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>平抛运动</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #ball{
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: palevioletred;
            transform: translate(100px,800px);
        }
        #target{
            width: 40px;
            height: 40px;
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <div id="grid">
        <div id="ball"></div>
    </div>
    <div style="height: 400px;"></div>
    <div style="display: flex;">
        <div style="width: 400px;height: 40px;background-color: palegoldenrod;"></div>
        <div id="target"></div>
    </div>
    <script src="./coord.js"></script>
    <script>
        // https://blog.csdn.net/java_tang_shi_wen/article/details/115127901
        // https://www.cnblogs.com/gating/p/j.html
        // a始终保持开头向下，所有，必须小于0，a的绝对值越大，抛物线越陡
        // y = ax^2 + bx + c; 由于是过原点（0,0），所以c = 0; => y = ax^2 + bx; 
        // b = (y - ax^2) / x;
        function parabola(el, target, duration = 300) {
            const coordContext = createCoord(el);
            const { x: targetX, y: targetY } = coordContext(target).getCoord();
            const a = -0.003;
            const y = targetY;
            const b = (y - a * Math.pow(targetX, 2))/targetX;
            // 从原点出发
            let lastX = 0, lastY = 0;
            const beginDate = +new Date();
            function play() {
                requestAnimationFrame(() => {
                    // 进度不能大于1
                    const progress = Math.min((Date.now() - beginDate)/duration, 1);
                    lastX = targetX * progress;
                    lastY = a * Math.pow(lastX, 2) + b * lastX;
                    coordContext(el).setCoord({ x: lastX, y: lastY });
                    if(Math.abs(lastX) >= Math.abs(targetX)) {
                        // 验证是否是600ms的duration时间
                        // console.log(Date.now() - beginDate)
                        return
                    }
                    play()
                })
            }
            play()
        }
        window.onload = () => {
            setTimeout(() => {
                const ball = document.querySelector('#ball');
                const target = document.querySelector('#target');
                parabola(ball, target);
            }, 1000)
        }
    </script>
</body>
</html>
